package com.xuxin.baby.page;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.search.weather.OnGetWeatherResultListener;
import com.baidu.mapapi.search.weather.WeatherDataType;
import com.baidu.mapapi.search.weather.WeatherResult;
import com.baidu.mapapi.search.weather.WeatherSearch;
import com.baidu.mapapi.search.weather.WeatherSearchOption;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.xuxin.baby.App;
import com.xuxin.baby.R;
import com.xuxin.baby.activity.ChildGreatRecordActivity;
import com.xuxin.baby.activity.ClassGrowthActivity;
import com.xuxin.baby.activity.DoctorActivity;
import com.xuxin.baby.activity.ReaderActivity;
import com.xuxin.baby.activity.ReaderVideoActivity;
import com.xuxin.baby.activity.SearchActivity;
import com.xuxin.baby.activity.VideoActivity;
import com.xuxin.baby.adapter.ImageAdapter;
import com.xuxin.baby.adapter.MainAdviseAdapter;
import com.xuxin.baby.adapter.MainClassAdapter;
import com.xuxin.baby.adapter.MainExpertsAdapter;
import com.xuxin.baby.adapter.MainMenuAdapter;
import com.xuxin.baby.adapter.MainRecordAdapter;
import com.xuxin.baby.adapter.MainTipsAdapter;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.BannerBean;
import com.xuxin.baby.bean.CategoryBean;
import com.xuxin.baby.bean.ChildGreatBean;
import com.xuxin.baby.bean.DoctorBean;
import com.xuxin.baby.bean.MainMenuBean;
import com.xuxin.baby.bean.ReaderVideoBean;
import com.xuxin.baby.bean.UserChildBean;
import com.xuxin.baby.contract.CategoryContract;
import com.xuxin.baby.contract.MainContract;
import com.xuxin.baby.event.BaseEventFragment;
import com.xuxin.baby.event.MainActivityEvent;
import com.xuxin.baby.event.MainFragmentEvent;
import com.xuxin.baby.fragment.menu.MenuCourseFragment;
import com.xuxin.baby.fragment.menu.MenuFragment;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.listener.OnMainRecordListener;
import com.xuxin.baby.network.Retrofit;
import com.xuxin.baby.popup.AttachChildPopup;
import com.xuxin.baby.presenter.CategoryPresenter;
import com.xuxin.baby.presenter.MainPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.RecycleUtils;
import com.xuxin.smartTabLayout.CommonTabLayout;
import com.xuxin.smartTabLayout.listener.CustomTabEntity;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.08.11 0011
 * 首页
 */
public class MainFragment extends BaseEventFragment implements MainContract.View, CategoryContract.View {
    private final MainContract.Presenter presenter = new MainPresenter(this);
    private final CategoryContract.Presenter presenter2 = new CategoryPresenter(this);
    RequestOptions options = RequestOptions.bitmapTransform(new CircleCrop());
    private final ArrayList<CustomTabEntity> mEntity = new ArrayList<>();
    private final ArrayList<Fragment> mFragments = new ArrayList<>();
    @BindView(R.id.main_refresh)
    SmartRefreshLayout main_refresh;
    @BindView(R.id.main_child)
    LinearLayout main_child;
    @BindView(R.id.main_child_image)
    ImageView main_change_image;
    @BindView(R.id.main_child_name)
    TextView main_child_name;
    @BindView(R.id.main_child_location)
    LinearLayout main_child_location;
    @BindView(R.id.main_child_city)
    TextView main_child_city;
    @BindView(R.id.main_child_weather)
    TextView main_child_weather;
    @BindView(R.id.main_banner)
    Banner<String, ImageAdapter> main_banner;
    @BindView(R.id.main_recycle_grow)
    RecyclerView main_recycle_grow;
    @BindView(R.id.main_dynamic)
    TextView main_dynamic;
    @BindView(R.id.main_recycle_tips)
    RecyclerView main_recycle_tips;
    @BindView(R.id.main_recycle_video)
    RecyclerView main_recycle_video;
    @BindView(R.id.main_recycle_reader)
    RecyclerView main_recycle_reader;
    @BindView(R.id.main_recycle_experts)
    RecyclerView main_recycle_experts;
    @BindView(R.id.main_recycle_class)
    RecyclerView main_recycle_class;

    @BindView(R.id.fragment_main_dynamic)
    LinearLayout fragment_main_dynamic;
    @BindView(R.id.fragment_main_video)
    LinearLayout fragment_main_video;
    @BindView(R.id.fragment_main_reader)
    LinearLayout fragment_main_reader;

    @BindView(R.id.main_menu_tab)
    CommonTabLayout main_menu_tab;
    @BindView(R.id.main_recycle_menu)
    RecyclerView main_recycle_menu;

    private MainTipsAdapter tipsAdapter;
    private MainAdviseAdapter videoAdapter;
    private MainAdviseAdapter readerAdapter;
    private MainExpertsAdapter expertsAdapter;
    private AttachChildPopup myAttachChildPopup;
    private MainMenuAdapter myMainMenuAdapter;
    private ACache aCache;
    private String memberId;//用户id
    private String tenantId;//租户id
    private String token;//授权token
    private String childId;//宝宝ID
    private String ageRge;//年龄段*/

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Override
    public View setContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void initView() {
        /**
         * 智能刷新
         */
        main_refresh.setEnableLoadMore(false);
        main_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                handler.sendEmptyMessage(0);
                handler.sendEmptyMessage(200);
            }
        });
        /**
         * 轮播图
         */
        main_banner.setIndicator(new CircleIndicator(getContext()));
        /**
         * 弹窗
         */
        myAttachChildPopup = new AttachChildPopup(context);
        myAttachChildPopup.setOnChildClickListener(new AttachChildPopup.OnChildClickListener() {
            @Override
            public void click(UserChildBean.ResultBean.ItemsBean itemsBean) {
                try {
                    myAttachChildPopup.dismiss();
                    childId = itemsBean.getId();
                    ageRge = itemsBean.getAgeRge();
                    main_child_name.setText(itemsBean.getNickname());
                    String image = Retrofit.image_url + itemsBean.getAvatar();
                    if (!StringUtils.isEmpty(image)) {
                        GlideApp.with(context).load(image).placeholder(R.mipmap.img_child_boy).apply(options).into(main_change_image);
                    }
                    aCache.put(BaseConstant.childId, childId);
                    popup.setTitle("加载中...").show();
                    handler.sendEmptyMessage(0);
                    handler.sendEmptyMessage(200);
                } catch (Exception e) {
                    e.printStackTrace();
                    myAttachChildPopup.dismiss();
                }
            }
        });
        /**
         * 首页改版
         */
        RecycleUtils.initNested(main_recycle_menu);
        myMainMenuAdapter = new MainMenuAdapter();
        main_recycle_menu.setAdapter(myMainMenuAdapter);
        myMainMenuAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                myMainMenuAdapter.refresh(position);
                if (main_menu_tab.getTabCount() > position) {
                    main_menu_tab.setCurrentTab(position);
                }
            }
        });
        /**
         * 成长日志
         */
        RecycleUtils.horizontal(main_recycle_grow);
        MainRecordAdapter myRecordAdapter = new MainRecordAdapter();
        main_recycle_grow.setAdapter(myRecordAdapter);
        myRecordAdapter.setOnItemClickListener(new OnMainRecordListener());
        /**
         * 小贴士
         */
        tipsAdapter = new MainTipsAdapter();
        RecycleUtils.horizontal(main_recycle_tips);
        main_recycle_tips.setAdapter(tipsAdapter);
        /**
         * 推荐视频
         */
        videoAdapter = new MainAdviseAdapter();
        RecycleUtils.init(main_recycle_video);
        main_recycle_video.setAdapter(videoAdapter);
        videoAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putString(BaseConstant.videoId, videoAdapter.getData().get(position).getId());
                    ActivityUtils.startActivity(bundle, VideoActivity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        /**
         * 推荐课程
         */
        readerAdapter = new MainAdviseAdapter();
        RecycleUtils.init(main_recycle_reader);
        main_recycle_reader.setAdapter(readerAdapter);
        readerAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putString(BaseConstant.readerId, readerAdapter.getData().get(position).getId());
                    ActivityUtils.startActivity(bundle, ReaderActivity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        /**
         * 专家介绍
         */
        expertsAdapter = new MainExpertsAdapter();
        RecycleUtils.horizontal(main_recycle_experts);
        main_recycle_experts.setAdapter(expertsAdapter);
        expertsAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putString("doctorId", expertsAdapter.getData().get(position).getId());
                    ActivityUtils.startActivity(bundle, DoctorActivity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        /**
         * 其它功能
         */
        RecycleUtils.init(main_recycle_class);
        MainClassAdapter myClassAdapter = new MainClassAdapter();
        main_recycle_class.setAdapter(myClassAdapter);
        myClassAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                switch (position) {
                    case 0:
                        ActivityUtils.startActivity(ClassGrowthActivity.class);
                        break;
                    case 1:
                        EventBus.getDefault().post(new MainActivityEvent());
                        break;
                    case 2:
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "早产儿专题早教课");
                        bundle.putString("categoryId", BaseConstant.categoryId_preterm);
                        bundle.putString("categoryType", "video");
                        ActivityUtils.startActivity(bundle, ReaderVideoActivity.class);
                        break;
                    case 3:
                        ToastUtils.showShort("功能尚在完善...");
                        // ActivityUtils.startActivity(ClassRiskActivity.class);
                        break;
                }
            }
        });
    }

    @Override
    public void initData() {
        SDKInitializer.initialize(App.getInstance());
        aCache = ACache.get(getContext());
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        String mCity = aCache.getAsString("mCity");
        String mWeather = aCache.getAsString("mWeather");
        if (!StringUtils.isEmpty(mCity) && !StringUtils.isEmpty(mWeather)) {
            LogUtils.e("有地址和天气信息 = " + mCity + " - " + mWeather);
            main_child_city.setText(mCity);
            main_child_weather.setText(mWeather);
            main_child_location.setVisibility(View.VISIBLE);
        }
        popup.setTitle("加载中...").show();
        handler.sendEmptyMessage(0);
        handler.sendEmptyMessage(200);
    }

    @Override
    public void onComplete() {
        dismiss();
        main_refresh.finishRefresh();
        main_refresh.finishLoadMore();
    }

    @Override
    @OnClick({R.id.main_child, R.id.search_main, R.id.fragment_main_dynamic,
            R.id.main_video_more, R.id.main_reader_more})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.main_child) {
            if (myAttachChildPopup.getData() > 0) {
                new XPopup.Builder(context)
                        .atView(main_child)
                        .asCustom(myAttachChildPopup)
                        .show();
            }
        } else if (id == R.id.search_main) {
            ActivityUtils.startActivity(SearchActivity.class);
        } else if (id == R.id.fragment_main_dynamic) {
            String dynamic = main_dynamic.getText().toString();
            if (!("暂无动态".equals(dynamic))) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("detail", true);
                bundle.putString("dynamicContent", dynamic);
                bundle.putString("dynamicImage", dynamicImage);
                ActivityUtils.startActivity(bundle, ChildGreatRecordActivity.class);
            } else {
                ActivityUtils.startActivity(ChildGreatRecordActivity.class);
            }
        } else if (id == R.id.main_video_more) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "推荐视频");
            bundle.putString("categoryId", BaseConstant.categoryId_main);
            bundle.putString("categoryType", "video");
            bundle.putString("ageRge", ageRge);
            ActivityUtils.startActivity(bundle, ReaderVideoActivity.class);
        } else if (id == R.id.main_reader_more) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "推荐视频");
            bundle.putString("categoryId", BaseConstant.categoryId_main);
            bundle.putString("categoryType", "common");
            bundle.putString("ageRge", ageRge);
            ActivityUtils.startActivity(bundle, ReaderVideoActivity.class);
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0://宝宝列表
                    LogUtils.e("宝宝列表");
                    presenter.getUserChild(tenantId, token, memberId);
                    break;
                case 1://轮播图
                    LogUtils.e("轮播图");
                    presenter.getBanner(tenantId, token);
                    break;
                case 2://最新动态
                    LogUtils.e("最新动态");
                    presenter.getChildGreat(tenantId, token, childId, "basic", 0);
                    break;
                case 3://小贴士
                    LogUtils.e("小贴士");
                    presenter.getTips(tenantId, token, BaseConstant.categoryId_tips);
                    break;
                case 4://推荐视频
                    LogUtils.e("推荐视频ageRge = " + ageRge);
                    presenter.getVideo(tenantId, token, BaseConstant.categoryId_main, ageRge);
                    break;
                case 5://推荐文章
                    LogUtils.e("推荐文章ageRge = " + ageRge);
                    presenter.getReader(tenantId, token, BaseConstant.categoryId_main, ageRge);
                    break;
                case 6://专家介绍
                    LogUtils.e("专家介绍");
                    presenter.getDoctor(tenantId, token, 0);
                    break;
                case 7:
                    presenter2.getCategory(tenantId, token, "course", BaseConstant.categoryId_health);
                    break;
                case 200:
                    permissions();
                    break;
                case 201://开始定位
                    try {
                        if (null != mLocationClient) {
                            mLocationClient.start();
                        }
                    } catch (Exception e) {
                        LogUtils.e("定位启动异常");
                        e.printStackTrace();
                    }
                    break;
                case 202://更新定位
                    presenter.updateCity(tenantId, token, memberId, (String) msg.obj);
                    break;
            }
            return false;
        }
    });

    @Override
    public void onSuccess(UserChildBean userChildBean) {
        LogUtils.e("宝宝列表更新");
        myAttachChildPopup.refresh(userChildBean);
        if (StringUtils.isEmpty(childId)
                && null != userChildBean.getResult()
                && null != userChildBean.getResult().getItems()
                && !userChildBean.getResult().getItems().isEmpty()) {
            LogUtils.e("宝宝初始化选择");
            main_child_name.setText(userChildBean.getResult().getItems().get(0).getNickname());
            childId = userChildBean.getResult().getItems().get(0).getId();
            ageRge = userChildBean.getResult().getItems().get(0).getAgeRge();
            String image = Retrofit.image_url + userChildBean.getResult().getItems().get(0).getAvatar();
            if (!StringUtils.isEmpty(image)) {
                GlideApp.with(context).load(image).placeholder(R.mipmap.img_child_boy).apply(options).into(main_change_image);
            }
            aCache.put(BaseConstant.childId, childId);
        }
        handler.sendEmptyMessage(1);
    }

    @Override
    public void onSuccess(BannerBean bannerBean) {
        LogUtils.e("轮播图更新");
        ImageAdapter imageAdapter = new ImageAdapter(bannerBean.getResult().getItems());
        main_banner.setAdapter(imageAdapter);
        handler.sendEmptyMessage(7);
    }

    private String dynamicImage;

    @Override
    public void onSuccess(ChildGreatBean childGreatBean) {
        LogUtils.e("动态列表更新");
        if (!childGreatBean.getResult().getItems().isEmpty()) {
            dynamicImage = childGreatBean.getResult().getItems().get(0).getPic1();
            main_dynamic.setText(childGreatBean.getResult().getItems().get(0).getEventContent());
        } else {
            main_dynamic.setText("暂无动态");
            dynamicImage = null;
        }
        fragment_main_dynamic.setVisibility(View.VISIBLE);
        handler.sendEmptyMessage(3);
    }

    @Override
    public void onSuccessTips(ReaderVideoBean readerVideoBean) {
        LogUtils.e("小贴士更新");
        tipsAdapter.setList(readerVideoBean.getResult().getItems());
        if (tipsAdapter.getData().size() > 0) {
            main_recycle_tips.setVisibility(View.VISIBLE);
        }
        handler.sendEmptyMessage(4);
    }

    @Override
    public void onSuccessVideo(ReaderVideoBean readerVideoBean) {
        LogUtils.e("推荐视频更新");
        videoAdapter.setList(readerVideoBean.getResult().getItems());
        if (videoAdapter.getData().size() > 0) {
            fragment_main_video.setVisibility(View.VISIBLE);
        }
        handler.sendEmptyMessage(5);
    }

    @Override
    public void onSuccessReader(ReaderVideoBean readerVideoBean) {
        LogUtils.e("推荐文章更新");
        readerAdapter.setList(readerVideoBean.getResult().getItems());
        if (readerAdapter.getData().size() > 0) {
            fragment_main_reader.setVisibility(View.VISIBLE);
        }
        handler.sendEmptyMessage(6);
    }

    @Override
    public void onSuccess(DoctorBean doctorBean) {
        LogUtils.e("专家介绍更新");
        expertsAdapter.setList(doctorBean.getResult().getItems());
        if (expertsAdapter.getData().size() > 0) {
            main_recycle_experts.setVisibility(View.VISIBLE);
        }
        main_recycle_class.setVisibility(View.VISIBLE);
    }

    public String[] permission = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};

    private void permissions() {
        PermissionUtils.permissionGroup(permission).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(@NonNull List<String> granted) {
                initLocation();
            }

            @Override
            public void onDenied(@NonNull List<String> deniedForever, @NonNull List<String> denied) {
                ToastUtils.showShort("权限已被拒绝，请打开权限");
            }
        }).request();
    }

    /**
     * 发起定位
     */
    public LocationClient mLocationClient = null;
    private WeatherSearch mWeatherSearch = null;

    public void initLocation() {
        LogUtils.e("发起定位");
        mLocationClient = new LocationClient(getContext());
        mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                if (!StringUtils.isEmpty(location.getCity())) {
                    String mCity = location.getCity().replace("市", "");
                    main_child_city.setText(mCity);
                    Message message = Message.obtain();
                    message.what = 202;
                    message.obj = mCity;
                    handler.sendMessage(message);
                    aCache.put("mCity", mCity);
                    LogUtils.e("定位成功 city = " + mCity);
                }
                String district = location.getAdCode();
                LogUtils.e("district = " + district);
                if (!StringUtils.isEmpty(district) && null != mWeatherSearch) {
                    mWeatherSearch.request(new WeatherSearchOption()
                            .weatherDataType(WeatherDataType.WEATHER_DATA_TYPE_ALL)
                            .districtID(district));
                }
            }
        });
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setNeedNewVersionRgc(true);
        option.setOpenGps(true);
        mLocationClient.setLocOption(option);
        handler.sendEmptyMessageDelayed(201, 2000);
        initWeather();
    }

    public void initWeather() {
        mWeatherSearch = WeatherSearch.newInstance();
        mWeatherSearch.setWeatherSearchResultListener(new OnGetWeatherResultListener() {
            @Override
            public void onGetWeatherResultListener(final WeatherResult weatherResult) {
                try {
                    if (null != weatherResult) {
                        String weather = weatherResult.getRealTimeWeather().getPhenomenon() + " " + weatherResult.getRealTimeWeather().getTemperature() + "℃";
                        main_child_weather.setText(weather);
                        aCache.put("mWeather", weather);
                        main_child_location.setVisibility(View.VISIBLE);
                        LogUtils.e("获取天气成功 mWeather = " + weather);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainFragmentEvent event) {
        LogUtils.e("刷新主页");
        childId = null;
        ageRge = null;
        main_child_name.setText("");
        aCache.remove(BaseConstant.childId);
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onSuccess(CategoryBean categoryBean) {
        if (null != categoryBean && null != categoryBean.getResult()
                && categoryBean.getResult().size() > 0) {
            if (main_menu_tab.getTabCount() == 0) {
                LogUtils.e("count = " + main_menu_tab.getTabCount());
                try {
                    List<MainMenuBean> list = new ArrayList<>();
                    list.add(new MainMenuBean("生长发育", ""));
                    mEntity.add(new MainEntity("生长发育", R.mipmap.ic_launcher, R.mipmap.ic_launcher));
                    mFragments.add(MenuFragment.newInstance());
                    for (int i = 0; i < categoryBean.getResult().size(); i++) {
                        list.add(new MainMenuBean(categoryBean.getResult().get(i).getCategoryName(), categoryBean.getResult().get(i).getIcons()));
                        mFragments.add(MenuCourseFragment.newInstance(categoryBean.getResult().get(i).getCategoryName(), categoryBean.getResult().get(i).getId()));
                        mEntity.add(new MainEntity(categoryBean.getResult().get(i).getCategoryName(), R.mipmap.ic_launcher, R.mipmap.ic_launcher));
                    }
                    myMainMenuAdapter.setList(list);
                    main_menu_tab.setTabData(mEntity, (FragmentActivity) context, R.id.main_menu_fragment, mFragments);
                    main_menu_tab.setCurrentTab(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                LogUtils.e("count = " + main_menu_tab.getTabCount());
            }
        }
    }

    public static class MainEntity implements CustomTabEntity {
        private final String title;
        private final int selected_id;
        private final int unselected_id;

        private MainEntity(String title, int selected, int unselected) {
            this.title = title;
            this.selected_id = selected;
            this.unselected_id = unselected;
        }

        @Override
        public String getTabTitle() {
            return title;
        }

        @Override
        public int getTabSelectedIcon() {
            return selected_id;
        }

        @Override
        public int getTabUnselectedIcon() {
            return unselected_id;
        }
    }
}